/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
 
/* $Id: udpserver.c 16 2007-06-10 02:10:04Z kf701.ye $ */

#include <sys/types.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include "kf701.h"

/** 
 * @brief UDP server use select
 *
 * Open a listen socket and read data,
 * then deleve data to FUNC, the user defined 
 * FUNC deal with data.
 * 
 * Note: dup addr and buf before create thread in FUNC
 *
 * @param port listen port
 * @param psize the UDP server MAX size protocol data
 * @param func user defined FUNC for deal with data
 */
void udp_server( uint16_t port, uint32_t psize, udp_data_func func)
{
	if( psize <= 0 || func == NULL )
	{
		sys_message("%s,%d: argu err\n", __FILE__, __LINE__);
		return ;
	}
	
	int sockfd = open_udp( port );
	if( -1 == sockfd )
	{
		sys_message("%s,%d: open sock err,%m\n", __FILE__, __LINE__);
		return ;
	}
	struct sockaddr_in  addr;
	socklen_t len = sizeof( struct sockaddr_in );
	
	fd_set readset;
	FD_ZERO(&readset);
	FD_SET( sockfd , &readset );
	
	int max_fd = sockfd , select_ret, nread;
	uint8_t buf[ psize ];
	
	while( 1 )
	{
		select_ret = select(max_fd+1, &readset, NULL, NULL, NULL);
		if ( select_ret < 0 )
		{
			sys_message("%s,%d: select err,%m\n", __FILE__, __LINE__);
			continue;
		}	
		if ( FD_ISSET (sockfd, &readset) )
		{
			nread = recvfrom(sockfd, (void*)buf, sizeof(buf) ,0, (struct sockaddr*)&addr, &len);
			if( nread <= 0 )
			{
				sys_message("%s: recvfrom err\n", __func__);
				continue;
			}
			sys_log("%s,%d: read from %s\n",__FILE__,__LINE__,inet_ntoa(addr.sin_addr));
			sys_log("%s,%d: read data len = %d\n", __FILE__, __LINE__, nread);
			/* Note: dup addr and buf before create thread in func */
			func( (struct sockaddr*)&addr, buf, nread );
		}
	}
}
